package sample.tangocho.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import sample.tangocho.service.AddCardService;
import sample.tangocho.service.AddCardServiceImpl;
import sample.tangocho.service.CreateTangochoService;
import sample.tangocho.service.CreateTangochoServiceImpl;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class ImportTangochoActivity extends Activity {

	private CreateTangochoService createTangochoService;

	private AddCardService addCardService;
	
	File dataDir;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.import_tangocho);

		// TODO DI
		createTangochoService = new CreateTangochoServiceImpl(
				getApplicationContext());
		addCardService = new AddCardServiceImpl(getApplicationContext());
		
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            dataDir = new File(Environment.getExternalStorageDirectory(), this.getPackageName());
            dataDir.mkdirs();
        }
        else{
            new AlertDialog.Builder(this).setMessage("SDカードが必要です").setPositiveButton("OK", null).show();
        }

	}

	public void importTangocho(View view) {

		EditText editTitle = (EditText) findViewById(R.id.edittext_filename);
		String fileName = editTitle.getText().toString();
		
		long tangochoId = createTangochoService.createTangocho(fileName);
		
		try {
			int cardCount = importCards(tangochoId, fileName);
			Toast.makeText(this, fileName + "をインポートしました。カード数：" + cardCount, Toast.LENGTH_LONG).show();
		} catch(IOException e) {
			e.printStackTrace();
			Toast.makeText(this, "インポートに失敗しました", Toast.LENGTH_SHORT).show();
		}
        finish();
	}

	private int importCards(long tangochoId, String fileName) throws IOException {

		FileInputStream input = new FileInputStream(new File(this.dataDir, fileName + ".txt"));
		BufferedReader reader = new BufferedReader(new InputStreamReader(input));
		String line;
		int count = 0;
		while ((line = reader.readLine()) != null) {
			String[] cardArray = line.split("\t");
			if (cardArray.length == 2) {
				addCardService.addCard(tangochoId, cardArray[0], cardArray[1]);
				count++;
			}
		}
		
		reader.close();
		
		return count;
	}
}
